<template>
  <BaseDialog title="上传" :visible.sync="dialogVisible">
    <div style="padding-right:20px;">
      <el-upload
        ref="upload"
        v-bind="$attrs"
        name="files"
        :headers="headers"
        accept=".xlsx,.xls"
        :file-list="fileList"
        :auto-upload="false"
        :on-change="handleUploadChange"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
      >
        <btn label="选择上传文件" icon="el-icon-upload" type="primary" />
      </el-upload>
      <p>1、点击下载<a :href="href">《导入模板》</a></p>
      <p>2、已填写好的，后缀为xlsx、xls格式的导入模板。</p>
    </div>
    <div slot="footer" class="dialog-footer">
      <btn label="取消" @click="dialogVisible=false" />
      <btn label="确定" type="primary" :loading="confirm_loading" @click="handleConfirm" />
    </div>
  </BaseDialog>
</template>

<script>
import { getToken } from '@/utils/auth'

export default {
  props: {
    href: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      dialogVisible: false,
      fileList: [],
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      confirm_loading: false
    }
  },
  watch: {
    dialogVisible(val) {
      this.fileList = []
    }
  },
  methods: {
    handleUploadChange(file) {
      this.fileList = [file]
    },
    handleUploadSuccess(res) {
      this.confirm_loading = false
      if (res.code === 0) {
        this.$message.success('导入成功')
        this.$emit('confirm')
        this.dialogVisible = false
      } else {
        const timer = setTimeout(() => {
          this.fileList = []
          clearTimeout(timer)
        })
        this.$message.error(res.msg)
      }
    },
    handleUploadError(res) {
      this.$message.error('上传失败')
      const timer = setTimeout(() => {
        this.fileList = []
        clearTimeout(timer)
      })
      this.confirm_loading = false
    },
    handleConfirm() {
      if (this.fileList.length) {
        this.confirm_loading = true
        this.$refs.upload.submit()
      } else {
        this.$message('请选择导入文件')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
a{
  color:#40832c;
}
</style>
